package com.example.infowall02.utils;

import org.springframework.stereotype.Component;
import toolgood.words.IllegalWordsSearch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class SensitiveWordFilter {
    // 定义 IllegalWordsSearch 实例
    private IllegalWordsSearch illegalWordsSearch;

    // 构造函数
    public SensitiveWordFilter() {
        this.illegalWordsSearch = new IllegalWordsSearch();
        // 加载敏感词并设置到 IllegalWordsSearch 中
        this.illegalWordsSearch.SetKeywords(loadSensitiveWords());
    }

    // 加载敏感词
    private List<String> loadSensitiveWords() {
        Set<String> words = new HashSet<>();
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("sensi_words.txt");
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = reader.readLine()) != null) {
                words.add(line.trim());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>(words);
    }

    // 过滤敏感词
    public String filter(String text) {
        // 使用 IllegalWordsSearch 的 Replace 方法替换敏感词
        return illegalWordsSearch.Replace(text, '*');
    }
}